package com.stone.design.mode.pipeline.netty.handler;

import com.google.common.collect.Maps;

import java.util.Map;

/**
 * ChannelHandler 适配器，主要是抽取一些公共方法进行实现
 *
 * @author wenpan 2024/01/21 17:12
 */
public class ChannelHandlerAdapter implements ChannelHandler {

    public static final ThreadLocal<Map<Class<?>, Boolean>> THREAD_LOCAL_MAP = new InheritableThreadLocal<Map<Class<?>, Boolean>>(){
        @Override
        protected Map<Class<?>, Boolean> initialValue() {
             super.initialValue();
             return Maps.newHashMap();
        }
    };

    /**
     * 如果handler不是共享的，则抛出异常
     */
    protected void ensureNotSharable() {
        if (isSharable()) {
            throw new IllegalStateException("ChannelHandler " + getClass().getName() + " is not allowed to be shared");
        }
    }

    /**
     * 判断handler是否是共享的
     */
    public boolean isSharable() {
        // 获取当前handler的Class
        Class<?> clazz = getClass();
        Map<Class<?>, Boolean> cache = THREAD_LOCAL_MAP.get();
        Boolean sharable = cache.get(clazz);
        if (sharable == null) {
            // 如果该handler上标注了 Sharable 注解，则说明是可以共享的，反之不可共享
            sharable = clazz.isAnnotationPresent(Sharable.class);
            cache.put(clazz, sharable);
        }
        return sharable;
    }
}
